import  React from 'react';
import  ReactDOM from 'react-dom';
import Swiper from 'swiper';
import 'swiper/css/swiper.css';
import { Toast } from 'antd-mobile';
import TweenMax from '../../../assets/js/utils/TweenMax';
import Css from '../../../assets/css/home/goods/index.css';
import IScroll from "../../../assets/js/utils/iscroll";
import {GoPageReplace,LocalParam,setScrollTop,lazyImg} from "../../../assets/js/utils";
import {connect} from 'react-redux';
import action from'../../../store/action';
import request from "../../../assets/js/utils/request";
class goodsCommodity extends React.Component{
    constructor(props){
        super(props);
        this.state={
            gid:props.location.search!==''?LocalParam(props.location.search).search:'',
            bMask:true,
            aArrt:[],
            iAMount:1,
            aEva:[],
            aEvaTotal:0

        }
        this.bMove=false
    }

    componentDidMount(){
        setScrollTop()
        this.handsDefaultTouch();
        this.eventIscroll();
        this.getGoodsCommoditydata();
        this.getGoodsCommodityArrtData();
        this.getGoodsCommodityEva();
    }
    //swiper切换
    commoditySwiper(){
        var refCommoditySwiper=this.refs['commoditySwiper']
        new Swiper(refCommoditySwiper, {
            autoplay: {
                disableOnInteraction: false,
            },
            pagination: {
                el: '.swiper-pagination',
            },
            loop : true,
            lazy: true,
        });
    }
    //删除默认touch事件
    handsDefaultTouch(){
        let commodityMask=this.refs['commodityMask'],commodityCart=this.refs['commodityCart'];
        commodityMask.addEventListener('touchmove',function (e) {
            e.preventDefault()
        });
        commodityCart.addEventListener('touchmove',function (e) {
            e.preventDefault()
        })
    }
    //关闭弹出
    closMask(){
        if(!this.bMove){
            this.setState({bMask:true})
        }
    }
    //显示弹出
    showMask(){
        this.setState({bMask:false})
    }
    //滚动
    eventIscroll(){
        let  temRef=this.refs['commodityArrt']
        this.myScroll = new IScroll(temRef, {
            scrollX: false,
            scrollY: true,
            preventDefault: false
        });
    }
    //收藏轻提示
    Collection(){
        let sUrl=window.base.config.baseUrl+'/goods/fav?uid='+this.props.state.redLogin.uid+'&gid='+this.state.gid.gid+'&token='+window.base.config.token;
        request(sUrl,'get').then(res=>{
            Toast.info(res.data, 1);
        })
    }
    //进入不记录历史页面
    goPagePush(url){
        GoPageReplace(this.props,url+'?gid='+this.state.gid.gid);
    }
    //点击改变属性状态
    changeArrtStyle(arrtIndex,vaulesIndex){
        let temArrt=this.props.state.redGoodsCommodityArrt.aArrt;
        if(!temArrt[arrtIndex].values[vaulesIndex].checked){
            for (let j in temArrt[arrtIndex].values) {
                temArrt[arrtIndex].values[j].checked=false;
            }
            temArrt[arrtIndex].values[vaulesIndex].checked=true;
        }else {
            temArrt[arrtIndex].values[vaulesIndex].checked=false;
        }
        this.setState({aArrt:temArrt})
    }
    //输入数量
    changeAmount(e){
        let temIAMount=this.state.iAMount;
        temIAMount=e.target.value.replace(/[a-zA-Z]|[\u4e00-\u9fa5]|[#|*|,|+|;|.]/g,'');
        this.setState({iAMount:temIAMount})
    }
    //增加数量
    addCount(){
        let temIAMount=this.state.iAMount;
        this.setState({iAMount:++temIAMount})
    }
    //减少数量
    decCount(){
        let temIAMount=this.state.iAMount;
        if (temIAMount>1){
            this.setState({iAMount:--temIAMount})
        }
    }
    //点击确定
    sureCart(){
        this.checkedArrt(()=>{
            if(!this.bMove){
                this.bMove=true
                let CartProImg=this.refs['commodityCartProImg'],
                    CartPro=this.refs['commodityCartPro'],
                    commodityCart=this.refs['commodityCart'],
                    CartIcn=ReactDOM.findDOMNode(document.getElementById('cartIcn')),
                    aCloneImg=CartProImg.cloneNode(true),
                    scrImgX=CartProImg.offsetLeft,
                    CartIcnX=CartIcn.offsetLeft,
                    CartIcnY=commodityCart.offsetTop+CartProImg.offsetTop;
                CartPro.appendChild(aCloneImg);
                aCloneImg.style.cssText='width:0.4rem;height:0.4rem;position:absolute;z-index:1;left:0.2rem;top:0.2rem;';
                TweenMax.to(aCloneImg, 2, {bezier:[{x:scrImgX, y:-100},{x:CartIcnX, y:-CartIcnY}],onComplete:()=>{
                        aCloneImg.remove();
                        this.bMove=false;
                        //获取商品属性
                        let attrs=[],param=[],temaArrt=this.state.aArrt;
                        if(temaArrt.length>0){
                            for (let i in temaArrt){
                                param=[]
                                if (temaArrt[i].values.length>0) {
                                    for (let j in temaArrt[i].values){
                                        if(temaArrt[i].values[j].checked){
                                            param.push({paramid:temaArrt[i].values[j].vid,title:temaArrt[i].values[j].value})
                                        }
                                    }
                                }
                                attrs.push({attrid:temaArrt[i].attrid,title:temaArrt[i].title,param:param})
                            }
                        }
                        //动画完成后将商品添加到redux
                        this.props.dispatch(action.actCart.actCart({
                            gid:this.state.gid.gid,
                            title:this.props.state.redGoodsCommodity.commodityImg.data.title,
                            amount:parseInt(this.state.iAMount),
                            price:this.props.state.redGoodsCommodity.commodityImg.data.price,
                            img:this.props.state.redGoodsCommodity.commodityImg.data.images[0],
                            checked:true,
                            freight:this.props.state.redGoodsCommodity.commodityImg.data.freight,
                            attrs:attrs
                        }))
                    }});
                TweenMax.to(aCloneImg,0.2,{rotation:360,repeat:-1})
            }
        })

    }
    //检测属性选择
    checkedArrt(callback){
        let temAArrt=this.props.state.redGoodsCommodityArrt.aArrt,bSelect=false,aName='';
        if(temAArrt.length>0){
           for(let i in temAArrt){
               bSelect=false;
               for (let j in temAArrt[i].values){
                    if(temAArrt[i].values[j].checked){
                        bSelect=true;
                        break
                    }
               }
               if(!bSelect){
                   aName=temAArrt[i].title;
                   break
               }
           }
           if(!bSelect){
               Toast.info('请选择'+aName,1)
           }else {
               callback()
           }
        }
    }
    //获取商品详情
    getGoodsCommoditydata(){
        let temGid=this.state.gid;
        this.props.dispatch(action.actDoodsCommodity.actDoodsCommodity(
            {
                temGid,
                success:(res)=>{
                    if(res.code===200){
                        this.commoditySwiper();
                        lazyImg();
                    }
                }
            }
        ));
    }
    //获取商品属性
    getGoodsCommodityArrtData(){
        let temGid=this.state.gid.gid;
        this.props.dispatch(action.actGoodsCommodityArr.actGoodsCommodityArrt(temGid))
    }
    //获取商品评价
    getGoodsCommodityEva(){
        let temGid=this.state.gid.gid;
        this.props.dispatch(action.actGoodsCOmmodityEval.actGoodsCommodityEval({
            temGid,
            success:(res)=>{
                lazyImg();
                this.setState({aEvaTotal:res.pageinfo.total})
            }
        }))
    }
    render(){
        return(
            <div>
                <div ref='commoditySwiper' className={Css['commoditySwiper']}>
                    <div className="swiper-wrapper">
                        {
                            this.props.state.redGoodsCommodity.commodityImg.code===200?
                                this.props.state.redGoodsCommodity.commodityImg.data.images.map((item,index)=>{
                                    return(
                                        <div key={index} className="swiper-slide"><img src={require('../../../assets/images/commen/lazyImg.jpg')} data-src={item} className={'swiper-lazy'} alt={item.title}/><div className="swiper-lazy-preloader "></div></div>
                                    )
                                }):''
                        }
                    </div>
                    <div className="swiper-pagination"></div>
                </div>
                <div className={Css['commodityAttr']}>
                    <div className={Css['commodityTitle']}>{ this.props.state.redGoodsCommodity.commodityImg.code===200?this.props.state.redGoodsCommodity.commodityImg.data.title:''}</div>
                    <div className={Css['commodityPric']+' mt20'}>¥{ this.props.state.redGoodsCommodity.commodityImg.code===200?this.props.state.redGoodsCommodity.commodityImg.data.price:''}</div>
                    <div className={Css['commoditySalesAttr']+' mt20'}>
                        <div className={Css['commodityExpress']}>快递{ this.props.state.redGoodsCommodity.commodityImg.code===200?this.props.state.redGoodsCommodity.commodityImg.data.freight:''}元</div>
                        <div className={Css['commoditySale']}>月销量{ this.props.state.redGoodsCommodity.commodityImg.code===200?this.props.state.redGoodsCommodity.commodityImg.data.sales:''}件</div>
                    </div>
                </div>
                <div className={Css['commodityEvaluate']+' mt20'}>
                    <div className={Css['commodityEvaluateTitle']}>商品评价（{this.props.state.redGoodsCommodityEval.aEvaArrt.code===200?this.props.state.redGoodsCommodityEval.aEvaArrt.pageinfo.total:'0'}）</div>
                    <ul>
                        {
                            this.props.state.redGoodsCommodityEval.aEvaArrt.code===200?
                                this.props.state.redGoodsCommodityEval.aEvaArrt.data.map((item,index)=>{
                                    return(
                                        <li key={index} className={'mt40'}>
                                            <div className={Css['commodityMember']}>
                                                <div className={Css['commodityMemberImg']}><img src={require('../../../assets/images/commen/lazyImg.jpg')} data-echo={item.head} alt={item.nickname}/></div>
                                                <div className={Css['commodityMemberNane']}>{item.nickname}</div>
                                            </div>
                                            <div className={Css['commodityDescribe']+' mt20'}>{item.content}</div>
                                            <div className={Css['commodityTime']+' mt10'}>{item.times}</div>
                                        </li>
                                    )
                                })
                            :''
                        }
                    </ul>
                    <div className={this.state.aEvaTotal>8?Css['commodityMore']:Css['commodityMore']+' hiden'} onClick={this.goPagePush.bind(this,'goods/details/evaluate')}>查看更多</div>
                </div>
                <div className={Css['commodityBottomWrap']}>
                    <div className={Css['commodityBottom']+' '+Css['commodityBottomL']} onClick={this.Collection.bind(this)}>收藏</div>
                    <div className={Css['commodityBottom']+' '+Css['commodityBottomR']} onClick={this.showMask.bind(this)}>加入购物车</div>
                </div>
                <div className={this.state.bMask?Css['commodityMask']:Css['commodityMask']+' '+Css['active']} ref='commodityMask'></div>
                <div className={this.state.bMask?Css['commodityCart']:Css['commodityCart']+' '+Css['active']} ref='commodityCart'>
                    <div className={Css['commodityCartPro']} ref='commodityCartPro'>
                        <div className={Css['commodityCartProImg']} ref='commodityCartProImg'><img src="//vueshop.glbuys.com/uploadfiles/1524556409.jpg" alt=""/></div>
                        <div className={Css['commodityCartProFont']}>
                            <div className={Css['commodityCartProFontTitle']}>{ this.props.state.redGoodsCommodity.commodityImg.code===200?this.props.state.redGoodsCommodity.commodityImg.data.title:''}</div>
                            <div className={Css['commodityCartProFontAttr']+' mt5'}>
                                <div className={Css['commodityCartProFontPrice']}>¥{ this.props.state.redGoodsCommodity.commodityImg.code===200?this.props.state.redGoodsCommodity.commodityImg.data.price:''}</div>
                                <div className={Css['commodityCartProFontNumber']}>商品编码:{this.state.gid.gid}</div>
                            </div>
                        </div>
                        <div className={Css['commodityCartProColse']}>
                            <div className={Css['commodityCartProColseFork']} onClick={this.closMask.bind(this)}><i className={'close fs40'}></i></div>
                            <div className={Css['commodityCartProColseLine']}></div>
                            <div className={Css['commodityCartProColseSpot']}></div>
                        </div>
                    </div>
                    <div ref='commodityArrt' className={Css['commodityArrt']}>
                        <div>
                            {
                                this.props.state.redGoodsCommodityArrt.aArrt.length>0?
                                    this.props.state.redGoodsCommodityArrt.aArrt.map((item,index)=>{
                                        return(
                                            <div className={Css['commodityCartAttr']} key={index}>
                                                <div className={Css['commodityCartAttrTitle']}>{item.title}</div>
                                                <ul className={'mt10'}>
                                                    {
                                                        item.values.length>0?
                                                            item.values.map((item2,index2)=>{
                                                                return(
                                                                    <li className={item2.checked?Css['active']:''} key={index2} onClick={this.changeArrtStyle.bind(this,index,index2)}>{item2.value}</li>
                                                                )
                                                            })
                                                            :'sasd'
                                                    }
                                                </ul>
                                            </div>
                                        )
                                    })
                                    :''
                            }

                        </div>
                    </div>
                    <div className={Css['commodityCartnumber']}>
                        <p>购买数量</p>
                        <div className={Css['commodityCount']}>
                            <i className={this.state.iAMount<=1?Css['active']:''} onClick={this.decCount.bind(this)}>-</i>
                            <div className={Css['commodityCountInput']}><input type="tel"  value={this.state.iAMount} onChange={this.changeAmount.bind(this)} /></div>
                            <i onClick={this.addCount.bind(this)}>+</i>
                        </div>
                    </div>
                    <div className={Css['commoditySure']} onClick={this.sureCart.bind(this)}>确定</div>
                </div>
            </div>
        )
    }
}
export default connect((state)=>{
    return{
        state:state
    }
})(goodsCommodity)